package com.huatai.bpmn.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.bpmn.entity.BasicEntity;
import com.huatai.bpmn.entity.DicEntity;
import com.huatai.bpmn.entity.ExternalParameterEntity;
import com.huatai.bpmn.entity.FormEntity;
import com.huatai.bpmn.mapper.ExternalParameterMapper;
import com.huatai.bpmn.service.BasicService;
import com.huatai.bpmn.service.DicService;
import com.huatai.bpmn.service.ExternalParameterService;
import com.huatai.bpmn.service.FormService;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yxy
 * @since 2023-08-14
 */
@Service
public class ExternalParameterServiceImpl extends ServiceImpl<ExternalParameterMapper, ExternalParameterEntity> implements ExternalParameterService {
	@Autowired
	private BasicService basicService;
	@Autowired
	private FormService formService;
	@Autowired
	private DicService dicService;

	/**
	 * 根据id查询表头和外部参数
	 * @param id
	 * @return
	 */
	@Override
	public HashMap<String, Object> selectColumAndParamById(Long id) {
		ExternalParameterEntity externalParameterEntity = this.getById(id);
		if (ObjectUtil.isEmpty(externalParameterEntity)){
			throw new RuntimeException("外部参数id错误");
		}
		String[] placeArr = getStrings(externalParameterEntity.getPlace());
		String[] notAllowChangedPlaceArr = getStrings(externalParameterEntity.getNotAllowChangePlace());

		HashMap<String, Object> paramMap = new HashMap<>();//存储表头和外部参数
		HashMap<String, HashMap<String,Object>> map = new HashMap<>();//存储表头
		Arrays.stream(placeArr).forEach(place->{
			//获取表单表头
			List<BasicEntity> colum = basicService.getColum(place);
			FormEntity formEntity = formService.getByPlace(place);
			HashMap<String, Object> dataMap = new HashMap<>();
			dataMap.put("colum",colum);
			dataMap.put("name",formEntity.getName());
			dataMap.put("allowChange",true);
			map.put(place,dataMap);
		});
		//根据不允许修改的place增加required字段用于前端判断
		for (String notAllowChangedPlace : notAllowChangedPlaceArr) {
			HashMap<String, Object> placeMap = map.get(notAllowChangedPlace);
			if (placeMap!=null){
				placeMap.put("allowChange",false);
			}
		}
		JSONArray paramConfigArray = JSONObject.parseArray(externalParameterEntity.getParam());
		List<DicEntity> dicEntityList = dicService.treeList();
		//添加selectDic类型的下拉框配置选项
		for (int i = 0; i < paramConfigArray.size(); i++) {
			JSONObject paramConfigJson = paramConfigArray.getJSONObject(i);
			if ("selectDic".equalsIgnoreCase(paramConfigJson.getString("type"))) {
				JSONObject children = paramConfigJson.getJSONObject("children");
				JSONArray options = new JSONArray();
				children.put("options", options);
				for (DicEntity dicEntity : dicEntityList) {
					if (paramConfigJson.getString("filedName").equals(dicEntity.getCode())) {
						for (DicEntity child : dicEntity.getChildren()) {
							JSONObject option = new JSONObject();
							option.put("optionName",child.getJsonTitle());
							option.put("optionValue",child.getId());
							options.add(option);
						}
						break;
					}
				}
			}
		}
		paramMap.put("files",JSONObject.parseArray(externalParameterEntity.getFilesConfig()));
		paramMap.put("param",paramConfigArray);
		paramMap.put("column",map);
		paramMap.put("risk",JSONObject.parseArray(externalParameterEntity.getRiskConfig()));
		return paramMap	;
	}


	/*public HashMap<String, Object> selectColumAndParamById(Long id) {
		ExternalParameterEntity externalParameterEntity = this.getById(id);
		if (ObjectUtil.isEmpty(externalParameterEntity)){
			throw new RuntimeException("外部参数id错误");
		}
		String[] placeArr = getStrings(externalParameterEntity.getPmpTable());
		String place = externalParameterEntity.getPlace();
		String[] notAllowChangedPlaceArr = getStrings(externalParameterEntity.getNotAllowChangePlace());

		HashMap<String, Object> paramMap = new HashMap<>();//存储表头和外部参数
		HashMap<String, HashMap<String,Object>> map = new HashMap<>();//存储表头
		Arrays.stream(placeArr).forEach(table->{
			//获取表单表头
			List<BasicEntity> colum = basicService.getColum(table);
			FormEntity formEntity = formService.getByPlace(table);
			HashMap<String, Object> dataMap = new HashMap<>();
			dataMap.put("colum",colum);
			dataMap.put("name",formEntity.getName());
			dataMap.put("allowChange",true);
			map.put(table,dataMap);
		});
		//根据不允许修改的place增加required字段用于前端判断
		for (String notAllowChangedPlace : notAllowChangedPlaceArr) {
			HashMap<String, Object> placeMap = map.get(notAllowChangedPlace);
			if (placeMap!=null){
				placeMap.put("allowChange",false);
			}
		}
		List<BasicEntity> colum = basicService.getColum(place);
		paramMap.put("files",JSONObject.parseArray(externalParameterEntity.getFilesConfig()));
		paramMap.put("param",colum);
		paramMap.put("column",map);
		return paramMap	;
	}*/

	@Override
	public Page<ExternalParameterEntity> page(Integer pageIndex, Integer pageSize) {
		Page<ExternalParameterEntity> page = this.page(new Page<>(pageIndex, pageSize));
		//获取记录
		List<ExternalParameterEntity> records = page.getRecords();
		//针对记录遍历获取place，并查询
		records.forEach(externalParameterEntity->{
			String place = externalParameterEntity.getPlace();
			if (StringUtil.isNotBlank(place)){
				String[] places = place.split(",");
				AtomicReference<String> placeKey = new AtomicReference<>("");
				AtomicReference<String> placeName = new AtomicReference<>("");
				Arrays.asList(places).forEach(x->{
					FormEntity formName = formService.getByPlace(x);
					placeKey.updateAndGet(v -> v + formName.getPlace()+",");
					placeName.updateAndGet(name-> name + formName.getName() + ",");
				});
				String placeKeys = placeKey.get().substring(0, placeKey.get().length()-1);
				String placeNames = placeName.get().substring(0,placeKey.get().length()-1);
				externalParameterEntity.setPlace(placeKeys);
				externalParameterEntity.setPlaceName(placeNames);
			}
		});
		return page;
//		return null;
	}

	private String[] getStrings(String arrStr) {
		if (StringUtil.isEmpty(arrStr)){
			return new String[]{};
		}
		return arrStr.split(",");
	}
}
